package com.heihei.videopreview;

import com.heihei.config.ConfigProperties;
import com.heihei.constant.MessageConstant;
import com.heihei.util.CollectionUtilF;
import com.heihei.util.FileUtilF;
import com.heihei.videopreview.entity.VideoAndPreCountEntity;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MergeVideoPreviewStart {
    private static CreateVideoPreview CVP = new CreateVideoPreview();

    private static List<VideoAndPreCountEntity> VP_LIST = new ArrayList<>();

    public static StringBuffer SB;

    public static void main(String[] args) throws IOException, InterruptedException {
        start();
    }

    /**
     * 方法描述: 开始执行
     *
     * @param
     * @Return
     * @throws
     * @author duanhengfei
     * @date 2021年02月14日 10:26:18
     */
    private static void start() throws IOException, InterruptedException {
        //初始化SB
        SB = new StringBuffer();
        System.out.println("请输入源目录：");
        File validSrcDirOrFile = FileUtilF.getValidSrcPath();
        handleCurrentDirOrFile(validSrcDirOrFile);
    }

    public static void handleCurrentDirOrFile(File validSrcDirOrFile) throws IOException, InterruptedException {
        if(validSrcDirOrFile.isFile()) {
            if(FileUtilF.isVideo(validSrcDirOrFile)) {
                VideoPreviewStart.startOneThread(validSrcDirOrFile, new File(validSrcDirOrFile.getParent(), validSrcDirOrFile.getName() + "preview" + MessageConstant.IMG_STYLE), ConfigProperties.VIDEO_MERGE_IMG_COUNT);
            } else {
                System.out.println(MessageConstant.ILLEGAL_FILE_STYLE);
                return;
            }
        } else {
            //文件夹
            handleDir(validSrcDirOrFile);
        }
    }

    /**
     * 方法描述: 处理文件夹下的视频文件，合并预览图
     *
     * @param
     * @param parentDir
     * @Return
     * @throws
     * @author duanhengfei
     * @date 2021年02月14日 10:31:11
     */
    private static void handleDir(File parentDir) throws IOException, InterruptedException {
        Integer count = ConfigProperties.VIDEO_MERGE_IMG_COUNT;
        List<File> videoFileList = FileUtilF.readAllFileConditional(parentDir, 2);
        List<File> selectedVideoList = CollectionUtilF.selectRandomElementFromList(videoFileList, count);
        List<BufferedImage> imgList = new ArrayList<>();
        addVPList(selectedVideoList, count);

        //开始处理图片（多线程操作）
        while(VP_LIST.size() > 0) {
            //限制最大运行线程的数量
            if(VideoPreviewStart.CURRENT_VIDEO_HANDLING_MAP.size() >= ConfigProperties.MAX_SYNC_HANDLE_VIDEO_COUNT) {
                Thread.sleep(3000);
                continue;
            }
            VideoAndPreCountEntity entity = VP_LIST.get(VP_LIST.size() - 1);
            String threadId = UUID.randomUUID().toString().replaceAll("-", "");
            VideoPreviewStart.CURRENT_VIDEO_HANDLING_MAP.put(threadId, entity.getVideoFile().getAbsolutePath());
            Thread vmThread = new Thread(new MergeVideoGenerateBufferedImgThread(threadId, CVP, entity.getVideoFile(), entity.getCount(), imgList));
            vmThread.start();
            VP_LIST.remove(VP_LIST.size() - 1);
        }
        while (true) {
            if(VideoPreviewStart.CURRENT_VIDEO_HANDLING_MAP.size() <= 0) {
                break;
            }
            Thread.sleep(3000);
        }
        CVP.write2ImgFile(imgList, new File(parentDir.getParent(), parentDir.getName() + "_preview" + MessageConstant.IMG_STYLE));
        System.out.println(MessageConstant.EVERYTHING_IS_OK);
        System.out.println("本次处理目录：");
        System.out.println(SB);
    }

    /**
     * 方法描述: 创建预览图，加进imgList中
     *
     * @param selectedVideoList
     * @param count
     * @Return
     * @throws
     * @author duanhengfei
     * @date 2021年02月14日 11:03:59
     */
    private static void addVPList(List<File> selectedVideoList, Integer count) {
        int basicEveryCount = count / selectedVideoList.size();
        for (File videoFile : selectedVideoList) {
            VP_LIST.add(new VideoAndPreCountEntity(videoFile, basicEveryCount));
        }
        int reminder = count % selectedVideoList.size();
        if(reminder > 0) {
            List<Integer> randomIndexList = CVP.random(VP_LIST.size(), reminder);
            for (Integer index : randomIndexList) {
                VideoAndPreCountEntity vp = VP_LIST.get(index);
                vp.setCount(vp.getCount() + 1);
            }
        }
    }
}